<?php
namespace jy_jicai;
defined('BY_JYA') or exit('error');
/*
	分销插件会员类
	如果将分销商各项数据在每次数据变动时计算好并存入数据库。
	那么分别需要做
		在设置上下级关系时，修改新上级的 下线数量、分销商数量、订单数量、订单佣金数量等数据
		在变更上下级关系时，修改原、新上级的各项参数
		在发生订单时，修改上级的订单相关参数
		在用户成为分销商时，修改上级的分销商数量相关数据
*/
class team extends \plugin{
	/*
		核实分销商
	*/
	public function checkmember($mid=0,$isexi=false){
			$mid=$mid?:$_SESSION['uid'];
			$member=$this->get('team',array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
			$teampage=$this->plugin_setting('teampage');
			$teampage['tagent']=$teampage['tagent']?:'团长';
			if(!$member['status']){
				$apply=$this->get('team',array('mid'=>$_SESSION['uid']),array('id','status'));
				if($apply['id'] && $apply['status']==0){
					if($isexi){
						exi('申请正在审核请耐心等待','error','jy_jicai/team.apply/');
					}else{
						return false;
					}
				}
				$member['can_apply']=false;
				//如果成为分销商无条件，此处自动申请成为分销商
				if($this->teamsetting['become']==0){
					//分销商无需审核，此处自动审核
					$member['can_apply']=true;
					$this->apply_agent($member['mid']);
					if($this->teamsetting['isshenhe'] && $isexi){
						exi('申请正在审核请耐心等待','error','jy_jicai/team.apply/');
					}else{
						exi('','','jy_jicai/team.index/');
					}
				}elseif($this->teamsetting['become']==3){
						//单笔自购金额
						$buyfee=pdo_get('jy_weishop_order',array('ispay'=>1,'mid'=>$mid),'','price desc');
						$buyfee=$buyfee['price'];
						$member['limit']=$this->teamsetting['oneorder_price'];
						$member['unit']='元';
						if($buyfee>=$this->teamsetting['oneorder_price']){
							$member['can_apply']=true;
							$this->apply_agent($member['mid']);
							$ispass=true;
						}
				}elseif($this->teamsetting['become']==4){
						//自购订单总金额
						$buyfee=pdo_getsum('jy_weishop_order',array('ispay'=>1,'mid'=>$mid,'uniacid'=>$_SESSION['uniacid']),'price');
						$buyfee=$buyfee?:0;
						$member['now']=$buyfee;
						$member['limit']=$this->teamsetting['buyallfee'];
						$member['unit']='元';
						if($buyfee>=$this->teamsetting['buyallfee']){
							$member['can_apply']=true;
							$this->apply_agent($member['mid']);
							$ispass=true;
						}
				}elseif($this->teamsetting['become']==5){
						//购买指定商品
						$become_goods=$this->teamsetting['become_goods'];
						$member['become_goods']=$become_goods;
						foreach($become_goods as &$bgv){
							$isbuy=pdo_count('jy_weishop_order_goods',array('mid'=>$member['mid'],'goodsid'=>$bgv['id'],'ispay'=>1));
							if($isbuy>0){
								$member['can_apply']=true;
								$this->apply_agent($member['mid']);
								$ispass=true;
								break;
							}
						}
				}elseif($this->teamsetting['become']==2){
					$member['can_apply']=true;
					if($isexi){
						exi('你还不是'.$teampage['tagent'].'，请前往申请！'.$_RQ['action'],'error','jy_jicai/team.apply/');
					}
				}elseif($this->teamsetting['become']==1){
					$member['desc']='暂时无法申请，只能由管理员后台指定';
				}
				if($this->teamsetting['isshenhe'] && $isexi && $ispass){
						exi('申请正在审核请耐心等待','error','jy_jicai/team.apply/');
				}elseif($ispass){
						$team=$this->get('team',array('mid'=>$_SESSION['uid']),array('id','status'));
						if($team['status']){
							exi('','','jy_jicai/team.index/');
						}
				}
				if($isexi){
						exi('你还不是'.$teampage['tagent'].'，请前往申请！'.$_RQ['action'],'error','jy_jicai/team.apply/');
				}
			}elseif($member['stop'] && $isexi){
				exi('你的'.$teampage['tagent'].'身份已禁用！','error','jy_jicai/team.apply/');
			}elseif((!$member['realname'] || !$member['mobile']) && $isexi){
				$newmember=$this->get('member',array('mid'=>$member['mid'],'uniacid'=>$_SESSION['uniacid']));
				if($this->teamsetting['isinfo']==1 && (!$newmember['realname'] || !$newmember['mobile'])){
					exi('请先完善信息','error','jy_jicai/team.info/');
				}else{
					
				}
			}
			return $member;
	}
	public function member_update($mid,$update=array()){
		pdo_update('jy_jicai_member',$update,array('mid'=>$mid));
		return true;
	}
	/*
		申请成为团队长
	*/
	public function apply_agent($mid,$area_code=''){
		$mid=$mid?:$_SESSION['uid'];
		$team=$this->get('team',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid));
		if($team['id'] && $team['status']==1){
			exi('您的申请已经通过！','error','jy_jicai/team.index/');
		}elseif($team['id'] && $team['status']==0){
			exi('您已经申请了团长！','error','jy_jicai/team.apply/');
		}
		if($team['id']){
			$new_apply=array(
				'status'=>0,
				'area_code'=>$area_code,
			);
			$this->update('team',$new_apply,array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid));
			$id=$team['id'];
		}else{
			$fromuser=pdo_getcolumn('jy_jicai_member',array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']),'fromuser');
			$new_apply=array(
				'uniacid'=>$_SESSION['uniacid'],
				'mid'=>$mid,
				'status'=>0,
				'area_code'=>$area_code,
				'fromuser'=>$fromuser?:$_SESSION['fromuser'],
				'createtime'=>TIMESTAMP,
			);
			pdo_insert('jy_jicai_team',$new_apply);
			$id=pdo_insertid();
		}
		if(!$this->teamsetting['isshenhe']){
			//分销商无需审核，此处自动审核
			$this->check_agent($id,1);
		}
		return $id;
	}
	/*
		审核团队长
	*/
	public function check_agent($agent_id,$status,$remark=''){
		if(!$agent_id || !$status){
			return;
		}
		$agent_area=$this->get('team',array('id'=>$agent_id));
		if(!$agent_area){
			return;
		}
		$update=array(
			'status'=>$status,
			'check_time'=>TIMESTAMP,
		);
		if($update['status']==1){
			$this->update_agent_level($agent_area['fromuser']);
		}else{
			$update['remark']=$remark;
		}
		$this->update('team',$update,array('id'=>$agent_id));
		return true;
	}
	public function set_parent($mid,$fromuser=0){
		$mid=$mid?:$_SESSION['uid'];
		if($mid==$fromuser || !$fromuser){
			return false;
		}
		//如果他的上级是我
		if($ta_agent_id==$mid){
			return true;
		}
		$this->update('team',array('fromuser'=>$fromuser,'updatetime'=>TIMESTAMP),array('mid'=>$mid));
		$this->update_agent_level($fromuser);
		return true;
	}
	/*
		禁用团长
	*/
	public function stop_agent($agent_id){
		$this->update('team',array('stop'=>1),array('mid'=>$agent_id));
	}
	/*
		恢复团长
	*/
	public function start_agent($agent_id){
		$this->update('team',array('stop'=>0),array('mid'=>$agent_id));
	}

	/*
		升级分销商等级
		先检测会员身份是否为正常分销商
		然后获取分销商当前等级的下一等级升级条件
		然后逐个条件对比，看是否满足升级条件
		如果全部满足，则升级到相应等级
		
		何时触发升级分销商等级检测呢？
		
	*/
	public function update_agent_level($mid,$self=false){
		//
		if(!$mid){
			return;
		}
		$agent=$this->get('team',array('mid'=>$mid));
		if(!$agent['mid']){
			return;
		}
		if($agent['status']!=1 && !$self){
			return;
		}
		$level=$this->get('teamlevel',array('id'=>$agent['level_id']));
		$level['level']=$level['level']?:0;
		$next_level=pdo_get('jy_jicai_teamlevel',array('uniacid'=>$_SESSION['uniacid'],'level >'=>$level['level']),'','level asc');
		if(!$next_level){
			return;
		}
		$conditions=json_decode($next_level['conditions'],true);
		$level_up_types=$this->model('model')->team_level_up_types();//获取当前设置的分销商等级升级条件
		if(!$level_up_types){
			return;
		}
		$up=true;
		$levels=pdo_get('jy_jicai_teamlevel',array('uniacid'=>$_SESSION['uniacid'],'level <'=>$level['level']),'','level desc');
		$on_level_id=$levels['id']?:0;
		$members=$this->getall('member',array('uniacid'=>$_SESSION['uniacid'],'fromuser'=>$agent['mid']),array('mid','fromuser'),'mid');
		if($members){
			$member_ids=array_keys($members);
			$member_ids[]=$agent['mid'];
		}else{
			$member_ids=$agent['mid'];
		}
		foreach($level_up_types as $type){
			if($type=='team_num'){
				//推荐次等级个数(同等级)
				$agent['team_num']=pdo_count('jy_jicai_team',array('level_id'=>$agent['level_id'],'fromuser'=>$member_ids));
				if($agent['team_num']<$conditions['team_num']){
					$up=false;
					break;
				}
			}elseif($type=='level_num'){
				//指定等级,指定等级人数（人）
				if($conditions['level_id']){
					$agent['level_num']=pdo_count('jy_jicai_team',array('level_id'=>$conditions['level_id']));
				}
				if($agent['level_num']<$conditions['level_num']){
					$up=false;
					break;
				}
			}elseif($type=='order_price'){
				//团订单总金额（元）,团订单总数（个）
				$agent['order_price']=pdo_getsum('jy_weishop_order',array('ispay'=>1,'mid'=>$member_ids),'price');
				if($agent['order_price']<$conditions['order_price']){
					$up=false;
					break;
				}
			}elseif($type=='order_num'){
				//团订单总金额（元）,团订单总数（个）
				$agent['order_num']=pdo_count('jy_weishop_order',array('ispay'=>1,'mid'=>$member_ids));
				if($agent['order_num']<$conditions['order_num']){
					$up=false;
					break;
				}
			}elseif($type=='self_order_num'){
				//自购订单总数,自购订单总金额
				if($self){
					$agent['self_order_num']=pdo_count('jy_weishop_order',array('ispay'=>1,'mid'=>$agent['mid']));
				}
				if($agent['self_order_num']<$conditions['self_order_num']){
					$up=false;
					break;
				}
			}elseif($type=='self_order_price'){
				//自购订单总数,自购订单总金额
				if($self){
					$agent['self_order_price']=pdo_getsum('jy_weishop_order',array('ispay'=>1,'mid'=>$agent['mid']),'price');
				}
				if($agent['self_order_price']<$conditions['self_order_price']){
					$up=false;
					break;
				}
			}elseif($type=='commission_money'){
				$agent['commission_money']=pdo_getsum('jy_jicai_feelog',array('mid'=>$agent['mid']),'money');
				if($agent['commission_money']<$conditions['commission_money']){
					$up=false;
					break;
				}
			}elseif($type=='oneorder_price'){
				//单笔自购金额
				$maxorder=pdo_get('jy_weishop_order',array('ispay'=>1,'mid'=>$agent['mid']),'','price desc');
				$agent['oneorder_price']=$maxorder['price'];
				if($agent['oneorder_price']<$conditions['oneorder_price']){
					$up=false;
					break;
				}
			}
		}
		if($up){
			$update=array(
				'level_id'=>$next_level['id'],
				'status'=>1,
			);
			$this->update('team',$update,array('id'=>$agent['id']));
			$this->update_agent_level($agent['fromuser']);
		}
		return true;
	}
	public function check_cangetfee($mid=0,$type=5){
		$mid=$mid?:$_SESSION['uid'];
		if($type==5){
			for($i=0;$i<5;$i++){
				$res=$this->check_file($this->teamsetting['daili_file'.$i],$i);
				if($res){
					return true;
				}
			}
		}else{
			for($i=0;$i<5;$i++){
				$res=$this->check_file($this->teamsetting['ping_file'.$i],$i);
				if($res){
					return true;
				}
			}
		}
		return false;
	}
	public function check_file($file,$key=0){
			if(!$file){
				return false;
			}
			//直推预选团队长多少人
			if($key==0){
				$area_num=$this->count('team',array('uniacid'=>$_SESSION['uniacid'],'fromuser'=>$mid));
				if($file<=$area_num){
					return true;
				}
			}elseif($key==1){
				//分红金额满多少元
				$params=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid);
				$ji_money=$this->sum('commission',$params,'money');
				if($file<=$ji_money){
					return true;
				}
			}elseif($key==2){
				//二级团队长满多少人
				$agent1_ids=$this->getall('team',array('fromuser'=>$mid),array('mid'),'mid');
				$agent1_ids=array_keys($agent1_ids);
				$agent2_num=$this->count('team',array('fromuser'=>$agent1_ids));
				if($file<=$agent2_num){
					return true;
				}
				
			}elseif($key==3){
				//三级团队长满多少人
				$agent1_ids=$this->getall('team',array('fromuser'=>$mid),array('mid'),'mid');
				$agent1_ids=array_keys($agent1_ids);
				$agent2_ids=$this->getall('team',array('fromuser'=>$agent1_ids),array('mid'),'mid');
				$agent2_ids=array_keys($agent2_ids);
				$agent3_num=$this->count('team',array('fromuser'=>$agent2_ids));
				if($file<=$agent3_num){
					return true;
				}
				
			}elseif($key==4){
				//四级团队长满多少人
				$agent1_ids=$this->getall('team',array('fromuser'=>$mid),array('mid'),'mid');
				$agent1_ids=array_keys($agent1_ids);
				$agent2_ids=$this->getall('team',array('fromuser'=>$agent1_ids),array('mid'),'mid');
				$agent2_ids=array_keys($agent2_ids);
				$agent3_ids=$this->getall('team',array('fromuser'=>$agent2_ids),array('mid'),'mid');
				$agent3_ids=array_keys($agent3_ids);
				$agent4_num=$this->count('team',array('fromuser'=>$agent3_ids));
				if($file<=$agent4_num){
					return true;
				}
			}elseif($key==5){
				//商城自购金额满
				$buyfee=pdo_getsum('jy_weishop_order',array('mid'=>$mid,'ispay'=>1),'price');
				if($file<=$buyfee){
					return true;
				}
			}elseif($key==6){
				//直推获得拼团金满
				if(!$this->plugin_exists('jy_pinggou')){
					return true;
				}
				$agent1_ids=$this->getall('team',array('fromuser'=>$mid),array('mid'),'mid');
				if($agent1_ids){
					$agent1_ids=array_keys($agent1_ids);
				}else{
					$agent1_ids=-1;
				}
				$fee=pdo_getsum('jy_pinggou_feelog',array('mid'=>$agent1_ids,'type'=>3),'fee');
				if($file<=$fee){
					return true;
				}
			}elseif($key==7){
				//直推累计购物满
				$agent1_ids=$this->getall('team',array('fromuser'=>$mid),array('mid'),'mid');
				if($agent1_ids){
					$agent1_ids=array_keys($agent1_ids);
				}else{
					$agent1_ids=-1;
				}
				$buyfee=pdo_getsum('jy_weishop_order',array('mid'=>$agent1_ids,'ispay'=>1),'price');
				if($file<=$buyfee){
					return true;
				}
			}
		return false;
	}
	//能否再获得奖金
	public function check_canaddfee($mid=0,$type=5){
		$mid=$mid?:$_SESSION['uid'];
		if($type==5){
			if($this->teamsetting['daili_jie']){
				//封顶时，满额了
				if($this->teamsetting['daili_type']==1){
					$fee=$this->sum('commission',array('type'=>5,'mid'=>$mid,'status <='=>1),'money');
					if($fee>=$this->teamsetting['daili_manfee']){
						return false;
					}
				}
			}else{
				$isgetfee=$this->check_isgetfee($mid,$type);
				if($isgetfee){
					return false;
				}
			}
		}
		if($type==6){
			if($this->teamsetting['ping_jie']){
				//封顶时，满额了
				if($this->teamsetting['ping_type']==1){
					$fee=$this->sum('commission',array('type'=>6,'mid'=>$mid,'status <='=>1),'money');
					if($fee>=$this->teamsetting['ping_manfee'] && $this->teamsetting['ping_manfee']){
						return false;
					}
				}
			}else{
				$isgetfee=$this->check_isgetfee($mid,$type);
				if($isgetfee){
					return false;
				}
			}
		}
		return true;
	}
	public function check_isgetfee($mid=0,$type=5){
		$mid=$mid?:$_SESSION['uid'];
		$params=array(
			'status'=>3,
			'fee_type'=>$type,
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$mid,
		);
		$balance=$this->get('balance',$params);
		if($balance['id']){
			return true;
		}else{
			return false;
		}
	}
	public function add_commission($canlog,$cangtitle='',$yaotitle=''){
		$member=$this->get('member',array('mid'=>intval($canlog['mid'])));
		$fromuser=$member['fromuser'];
		$this->teamfee=0;
		for($i=0;$i<9;$i++){
			if(!$fromuser){
				break;
			}
			$team=$this->get('team',array('mid'=>$fromuser));
			if($team['id']){
				$this->fee_commission($team,$canlog,$cangtitle.$yaotitle);
			}
			$fromuser=pdo_getcolumn('jy_jicai_team',array('mid'=>$fromuser,'uniacid'=>$_SESSION['uniacid']),'fromuser');
		}
		return true;
	}
	public function fee_commission($team,$canlog=array(),$cangtitle='',$yaotitle=''){
		$level=pdo_get('jy_jicai_teamlevel',array('uniacid'=>$_SESSION['uniacid'],'id'=>$team['level_id']));
		$red_per=$level['red_per'];
		$fee=$canlog['getfee'];
		if($fee>0 && $red_per>0){
			$fee=$fee*$red_per/100;
			$fee -=$this->teamfee;
			$this->teamfee +=$fee;
			if($fee>0){
				$new_commission=array(
						'uniacid'=>$_SESSION['uniacid'],
						'mid'=>$team['mid'],
						'yaoid'=>$canlog['yaoid'],
						'cangid'=>$canlog['cangid'],
						'canlogid'=>$canlog['id'],
						'jifen'=>$fee,
						'remark'=>ijson_encode($remark),
						'createtime'=>TIMESTAMP,
						'status'=>2,
						'type'=>2,
				);
				$this->insert('commission',$new_commission);
				$new_commission['fee']=$fee;
				$this->model('model')->add_feelog($new_commission,1);
				pdo_update('jy_jicai_member',array('baofee +='=>$fee),array('mid'=>$team['mid'],'uniacid'=>$_SESSION['uniacid']));
			}
		}
		return true;
	}
}